<?php


namespace common\service;


use Exception;
use core\exception\BadException;
use yzh52521\JwtAuth\exception\JwtException;
use yzh52521\JwtAuth\handle\RequestToken;
use yzh52521\JwtAuth\JwtAuth;
use yzh52521\JwtAuth\user\AuthorizationUserInterface;

class JwtService
{
    static function getToken($store = null)
    {
        $requestToken = new RequestToken();
        return $requestToken->get(\yzh52521\JwtAuth\facade\JwtAuth::getConfig($store)->getType());
    }

    /**
     * @param null $store
     * @return AuthorizationUserInterface
     * @throws BadException
     */
    static function checkJwtToken($store = null): AuthorizationUserInterface
    {

        //验证token
        $jwtAuth = new JwtAuth($store);
        try {
            $requestToken = new RequestToken();
            $token = $requestToken->get(\yzh52521\JwtAuth\facade\JwtAuth::getConfig($store)->getType());
            if (!$token) {
                throw new BadException("登录校验已失效, 请重新登录", 401);
            }

            $data = $jwtAuth->verify($token);
        } catch (JwtException $e) {
            throw new BadException("登录校验已失效, 请重新登录", 401);
        } catch (Exception $exception) {
            throw new BadException("登录校验已失效, 请重新登录", 401);
        }
        if ($data["source"] !== $store) {
            throw new BadException("登录校验已失效, 请重新登录", 401);
        }
        return $jwtAuth->getUser();
    }

    static function verifyToken($token, $store = null): AuthorizationUserInterface
    {
        //验证token
        $jwtAuth = new JwtAuth($store);
        try {
            $data = $jwtAuth->verify($token);
        } catch (JwtException $e) {
            throw new BadException("登录校验已失效, 请重新登录", 401);
        } catch (Exception $exception) {
            throw new BadException("登录校验已失效, 请重新登录", 401);
        }
        if ($data["source"] !== $store) {
            throw new BadException("登录校验已失效, 请重新登录", 401);
        }
        return $jwtAuth->getUser();
    }

    static function generateToken($uid, $store = null)
    {
        $jwtAuth = new JwtAuth($store);
        return $jwtAuth->token($uid, ['source' => $store])->toString();
    }

    static function logout($store = null)
    {
        $jwtAuth = new JwtAuth($store);
        $requestToken = new RequestToken();
        $token = $requestToken->get(\yzh52521\JwtAuth\facade\JwtAuth::getConfig($store)->getType());

        return $jwtAuth->logout($token);
    }
}